package cn.yr.netty;

import cn.yr.common.core.domain.entity.YrMessage;
import cn.yr.service.YrMessageService;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.*;

/**
 * @author Lang 1102076808@qq.com
 * @description 消息分发处理
 * @date 2021-01-10 19:24
 */
@Component
public class MessageDispatcher {

	@Autowired
	private NettyChannelManager nettyChannelManager;
	@Autowired
	private YrMessageService yrMessageService;

	private final ExecutorService executor =  new ThreadPoolExecutor(5, 200, 1000, TimeUnit.MILLISECONDS,
			new SynchronousQueue<>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

	public void execute(YrMessage message, Channel channel){
		message = saveDb(message);
		System.out.println(message.getId());
		switch (message.getType()){
			case 1:nettyChannelManager.send(message.getReceiver().toString(),message);
				break;
			case 2:
				nettyChannelManager.sendAll(message,channel);
				break;
			default:nettyChannelManager.send(message.getReceiver().toString(),message);
				break;
		}
	}

	public YrMessage saveDb(YrMessage message){
		message.setCreateTime(new Date());
		return yrMessageService.saveMessage(message);
	}

}
